﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using JGSoft.U9CRTAPIEX.DTOs;
using JGSoft.U9CRTAPIEX.DTOs.RequestDTOs;
using JGSoft.U9CRTAPIEX.DTOs.ResultDTOs;
using UFIDA.U9.Base;
using UFIDA.U9.CBO.Pub.Controller;
using UFIDA.U9.CBO.SCM.Bin;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.CBO.SCM.PropertyTypes;
using UFIDA.U9.CBO.SCM.Warehouse;
using UFIDA.U9.ISV.PO;
using UFIDA.U9.ISV.PO.Proxy;
using UFIDA.U9.ISV.TransferInISV;
using UFIDA.U9.ISV.TransferInISV.Proxy;
using UFIDA.U9.PM.PO;
using UFSoft.UBF.Business;
using UFSoft.UBF.MVC;
using UFSoft.UBF.MVC.Common;
using UFSoft.UBF.PL;
using UFSoft.UBF.Transactions;

namespace JGSoft.U9CRTAPIEX.Controllers
{
    public class TransController : OpenAPIController
    {


        /// <summary>
        /// 创建调入单
        /// </summary>
        /// <param name="transferInRDatas"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult<List<ResultDTORData>> CreateTransferIn([FromBody] List<TransferInRData> transferInRDatas)
        {
            ApiResult<List<ResultDTORData>> result = new ApiResult<List<ResultDTORData>>();
            List<ResultDTORData> resultDTOs = new List<ResultDTORData>();
            ResultDTORData resultDTO = new ResultDTORData();
            foreach (TransferInRData data in transferInRDatas)
            {
                resultDTO = new ResultDTORData();
                resultDTO.IsSucess = false;
                resultDTO.OtherID = data.OtherID;
                using (UBFTransactionScope scope = new UBFTransactionScope(TransactionOption.RequiresNew))
                {
                    try
                    {

                        List<CommonArchiveDataDTOData> transferInKeyList = new CommonCreateTransferInSVProxy
                        {
                            TransferInDTOList = GetTransferInDTO(data)
                        }.Do();
                        if (transferInKeyList != null && transferInKeyList.Count > 0)
                        {
                            resultDTO.IsSucess = true;
                            resultDTO.Code = transferInKeyList[0].Code;
                            resultDTO.ID = transferInKeyList[0].ID;
                        }
                        else
                        {
                            resultDTO.IsSucess = false;
                            resultDTO.ErrorMsg = "生单返回结果为空，生成调入单失败！";
                        }


						TransferInBatchCommitSRVProxy proxy = new TransferInBatchCommitSRVProxy();
						proxy.DocList = transferInKeyList;
						proxy.Do();

						TransferInBatchApproveSRVProxy Approvedproxy = new TransferInBatchApproveSRVProxy();
						Approvedproxy.DocList = transferInKeyList;
						Approvedproxy.Do();

						scope.Commit();
                    }
                    catch (Exception ex)
                    {
                        scope.Rollback();
                        resultDTO.IsSucess = false;
                        resultDTO.ErrorMsg = ex.Message;
                    }
                    resultDTOs.Add(resultDTO);
                }
            }
            result.Data = resultDTOs;
            return result;
        }


		private static List<IC_TransferInDTOData> GetTransferInDTO(TransferInRData data)
		{
			List<IC_TransferInDTOData> dtos = new List<IC_TransferInDTOData>();
			IC_TransferInDTOData transferInDTO = new IC_TransferInDTOData();
			transferInDTO.BusinessDate = data.BusinessDate;
			transferInDTO.Org = new CommonArchiveDataDTOData();
			if (!string.IsNullOrEmpty(data.Org_Code))
			{
				transferInDTO.Org.Code = data.Org_Code;
			}
			else
			{
				transferInDTO.Org.ID = Context.LoginOrg.ID;
			}
			transferInDTO.TransferDirection = data.TransferDirection;
			transferInDTO.TransferType = data.TransferType;
			if (!string.IsNullOrEmpty(data.TransInDocType_Code))
			{
				transferInDTO.TransInDocType = new CommonArchiveDataDTOData();
				transferInDTO.TransInDocType.Code = data.TransInDocType_Code;
			}
			transferInDTO.DescFlexField = ToolUtils.ConvertDescFlexFieldToData(data.DescFlexField);
			foreach (TransInLineRData item in data.TransInLines)
			{
				IC_TransInLineDTOData transLine = new IC_TransInLineDTOData();
				transLine.ItemInfo = new ItemInfoData();
				if (item.ItemInfo != null)
				{
					transLine.ItemInfo = ToolUtils.ToItemInfoData(item.ItemInfo);
				}
				transLine.CostUOMQty = item.CostUOMQty;
				transLine.StoreUOMQty = item.StoreUOMQty;
				if (!string.IsNullOrEmpty(item.StoreUOM_Code))
				{
					transLine.StoreUOM = new CommonArchiveDataDTOData();
					transLine.StoreUOM.Code = item.StoreUOM_Code;
				}
				transLine.DescFlexSegments = ToolUtils.ConvertDescFlexFieldToData(item.DescFlexField);
				if (!string.IsNullOrEmpty(item.Project_Code))
				{
					transLine.Project = new CommonArchiveDataDTOData();
					transLine.Project.Code = item.Project_Code;
				}
				if (!string.IsNullOrEmpty(item.Task_Code))
				{
					transLine.Task = new CommonArchiveDataDTOData();
					transLine.Task.Code = item.Task_Code;
				}
				if (!string.IsNullOrEmpty(item.TransInWh_Code))
				{
					transLine.TransInWh = new CommonArchiveDataDTOData();
					transLine.TransInWh.Code = item.TransInWh_Code;
				}
				if (!string.IsNullOrEmpty(item.LotInfo_Code))
				{
					transLine.LotInfo = new LotInfoData();
					transLine.LotInfo.LotCode = item.LotInfo_Code;
				}
				if (!string.IsNullOrEmpty(item.TransInSuppInfo_Code))
				{
					transLine.TransInSuppInfo = new UFIDA.U9.CBO.SCM.Supplier.SupplierMISCInfoData();
					transLine.TransInSuppInfo.Code = item.TransInSuppInfo_Code;
				}
				if (!string.IsNullOrEmpty(item.TransInBinCode))
				{
					Bin bin = GetBinByCode(item.TransInBinCode,item.TransInWh_Code);
					if (bin != null)
					{
						transLine.TransInBins = new List<IC_TransInBinDTOData>();
						IC_TransInBinDTOData binData = new IC_TransInBinDTOData();
						binData.BinInfo = new BinInfoData();
						binData.BinInfo.Bin = bin.ID;
						binData.BinInfo.Code = bin.Code;
						binData.BinInfo.Name = bin.Name;
						binData.StoreUOMQty = item.StoreUOMQty;
						transLine.TransInBins.Add(binData);
					}
				}

				if (item.TransInSubLines != null)
				{
					foreach (TransInSubLineRData item2 in item.TransInSubLines)
					{
						IC_TransInSubLineDTOData transSubLine = new IC_TransInSubLineDTOData();
						transSubLine.CostUOMQty = item2.CostUOMQty;
						transSubLine.StoreUOMQty = item2.StoreUOMQty;
						if (!string.IsNullOrEmpty(item.StoreUOM_Code))
						{
							transSubLine.StoreUOM = new CommonArchiveDataDTOData();
							transSubLine.StoreUOM.Code = item.StoreUOM_Code;
						}
						transSubLine.DescFlexSegments = ToolUtils.ConvertDescFlexFieldToData(item.DescFlexField);
						if (!string.IsNullOrEmpty(item2.Project_Code))
						{
							transSubLine.Project = new CommonArchiveDataDTOData();
							transSubLine.Project.Code = item.Project_Code;
						}
						if (!string.IsNullOrEmpty(item2.Task_Code))
						{
							transSubLine.Task = new CommonArchiveDataDTOData();
							transSubLine.Task.ID = -100L;
							transSubLine.Task.Code = item2.Task_Code;
						}
						if (!string.IsNullOrEmpty(item2.TransOutOrg_Code))
						{
							transSubLine.TransOutOrg = new CommonArchiveDataDTOData();
							transSubLine.TransOutOrg.Code = item2.TransOutOrg_Code;
						}
						if (!string.IsNullOrEmpty(item2.TransOutWh_Code))
						{
							transSubLine.TransOutWh = new CommonArchiveDataDTOData();
							transSubLine.TransOutWh.Code = item2.TransOutWh_Code;
						}
						if (!string.IsNullOrEmpty(item2.TransOutSuppInfo_Code))
						{
							transSubLine.TransOutSuppInfo = new UFIDA.U9.CBO.SCM.Supplier.SupplierMISCInfoData();
							transSubLine.TransOutSuppInfo.Code = item2.TransOutSuppInfo_Code;
						}
						if (!string.IsNullOrEmpty(item.LotInfo_Code))
						{
							transSubLine.LotInfo = new LotInfoData();
							transSubLine.LotInfo.LotCode = item2.LotInfo_Code;
						}
						if (!string.IsNullOrEmpty(item2.TransInBins))
						{
							Bin bin = GetBinByCode(item2.TransInBins,item2.TransOutWh_Code);
							if (bin != null)
							{
								transSubLine.TransInBins = new List<IC_TransInBinDTOData>();
								IC_TransInBinDTOData binData = new IC_TransInBinDTOData();
								binData.BinInfo = new BinInfoData();
								binData.BinInfo.Bin = bin.ID;
								binData.BinInfo.Code = bin.Code;
								binData.BinInfo.Name = bin.Name;
								binData.StoreUOMQty = item.StoreUOMQty;
								transSubLine.TransInBins.Add(binData);
							}
						}
						transLine.TransInSubLines.Add(transSubLine);
					}
				}
				transferInDTO.TransInLines.Add(transLine);
			}
			dtos.Add(transferInDTO);
			return dtos;
		}

		/// <summary>
		/// 获取库位信息，先按名称找， 再按编码找
		/// </summary>
		/// <param name="transInBinCode"></param>
		/// <returns></returns>
		// Token: 0x06000045 RID: 69 RVA: 0x000097DC File Offset: 0x000079DC
		private static Bin GetBinByCode(string transInBinCode,string whCode)
		{
			Warehouse warehouse = Warehouse.Finder.Find($"Code = '{whCode}'");
			Bin bin = null;
			if (!string.IsNullOrEmpty(transInBinCode))
			{
				if (warehouse != null)
				{
					bin = Bin.Finder.Find("Name=@Name and Org=@Org and Effective.IsEffective=1 and Warehouse = @Warehouse", new OqlParam[]
					{
					new OqlParam("Name", transInBinCode),
					new OqlParam("Org", Context.LoginOrg.ID),
					new OqlParam("Warehouse", warehouse.ID)
					});
					if (bin == null)
					{
						bin = Bin.Finder.Find("Code=@Code and Org=@Org and Effective.IsEffective=1  and Warehouse = @Warehouse", new OqlParam[]
						{
						new OqlParam("Code", transInBinCode),
						new OqlParam("Org", Context.LoginOrg.ID),
						new OqlParam("Warehouse", warehouse.ID)
						});
					}
				}
				else
				{
					bin = Bin.Finder.Find("Name=@Name and Org=@Org and Effective.IsEffective=1 ", new OqlParam[]
						{
					new OqlParam("Name", transInBinCode),
					new OqlParam("Org", Context.LoginOrg.ID)
						});
					if (bin == null)
					{
						bin = Bin.Finder.Find("Code=@Code and Org=@Org and Effective.IsEffective=1", new OqlParam[]
						{
						new OqlParam("Code", transInBinCode),
						new OqlParam("Org", Context.LoginOrg.ID)
						});
					}
				}
			}
			return bin;
		}
	}
}
